package com.leetcode.dynamic_programming;

import java.util.Arrays;

/**
 * @author Dennis Li
 * @date 2020/7/19 10:53
 */
public class UniquePath_62 {

    public int uniquePaths(int m, int n) {
        if (m == 1 || n == 1) return 1;
        int[][] dp = new int[m][n];
        dp[0][0] = 1;
        // 执行初始化
        for (int i = 1; i < m; i++) dp[i][0] = 1;
        for (int i = 1; i < n; i++) dp[0][i] = 1;
        for (int i = 1; i < m; i++)
            for (int j = 1; j < n; j++)
                // 状态方程转化
                dp[i][j] = dp[i - 1][j] + dp[i][j - 1];
        return dp[m - 1][n - 1];
    }

    // 空间复杂度为O(n) -- 上面的一行不需要再用到
    public int uniquePathsBetter(int m, int n) {
        if (m == 1 || n == 1) return 1;
        int[] dp = new int[n];
        // 执行初始化
        for (int i = 0; i < n; i++) dp[i] = 1;
        for (int i = 1; i < m; i++)
            for (int j = 1; j < n; j++)
                dp[j] = dp[j - 1] + dp[j];
        // 状态方程转化
        return dp[n - 1];
    }

    public int uniquePathBetter2(int m, int n) {
        int[] dp = new int[n];
        Arrays.fill(dp, 1);
        for (int i = 1; i < m; i++) {
            for (int j = 1; j < n; j++) {
                dp[j] = dp[j] + dp[j - 1];
            }
        }
        return dp[n - 1];
    }

}
